﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DataAccess.Repository;
using DataAccess.Models;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.IO;
using System.Web;

namespace KPI
{
	public partial class KPIProgressData : BasePage
	{
		private IGroupRepository _GroupRepository;

		protected void Page_Init(object sender, EventArgs e)
		{
			if(TheCurrentLoginUser == null)
			{
				Response.Redirect("~/Login.aspx");
			}

			if(!TheCurrentLoginUser.RoleName.Equals("administrators"))
			{
				Response.Redirect("~/NoPermission.aspx");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindGroups();
			}
		}

		protected void btnExport_Click(object sender, EventArgs e)
		{
			var lstData = GetDataSource();

			if(lstData != null && lstData.Count > 0)
			{
				var hssfworkbook = new XSSFWorkbook();

				foreach(var item in lstData)
				{
					var sheetItem = hssfworkbook.CreateSheet(item.GroupShortName);

					BuildGroupSheet(sheetItem, item);
				}

				using(var exportData = new MemoryStream())
				{
					hssfworkbook.Write(exportData);
					var buffer = exportData.ToArray();
					string saveAsFileName = HttpUtility.UrlEncode("KPI指标完成情况统计报表.xlsx", System.Text.Encoding.UTF8);
					HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
					HttpContext.Current.Response.ContentType = "application/vnd.ms-excel.12";
					HttpContext.Current.Response.Charset = "";
					HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
					HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString());
					HttpContext.Current.Response.Clear();
					HttpContext.Current.Response.BinaryWrite(buffer);
					HttpContext.Current.Response.End();
				}
			}
		}

		protected void ddlGroups_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		protected void rptGroupKPIProgressData_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			var data = e.Item.DataItem as DataAccess.Models.Group;

			if(data != null)
			{
				var theGroupKPIProgressData1 = e.Item.FindControl("theGroupKPIProgressData1") as Controls.TheGroupKPIProgressData;

				theGroupKPIProgressData1.TheGroup = data;
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindData();
		}

		protected void Page_UnLoad(object sender, EventArgs e)
		{
			if(_GroupRepository != null)
			{
				((IDisposable)_GroupRepository).Dispose();
			}
		}

		private void BindGroups()
		{
			if(ddlGroups.Items.Count == 0)
			{
				ddlGroups.Items.Add(new ListItem("--------所有单位--------------", "0"));

				if(_GroupRepository == null)
				{
					_GroupRepository = new GroupRepository();
				}

				var groups = _GroupRepository.GetAllGroups();

				if(groups != null && groups.Count > 0)
				{
					var groupCategory = groups.Select(g => g.TheGroupCategory).Distinct();

					if(groupCategory != null)
					{
						var lstGroupCategory = new List<GroupCategory>();

						foreach(var gcItem in groupCategory)
						{
							if(lstGroupCategory.Count(gc => gc.GroupCategoryID == gcItem.GroupCategoryID) == 0)
							{
								lstGroupCategory.Add(gcItem);
							}
						}

						foreach(var gcItem in lstGroupCategory)
						{
							var gcListItem = new ListItem("--------" + gcItem.GroupCategoryName + "--------", gcItem.GroupCategoryID.ToString());

							ddlGroups.Items.Add(gcListItem);

							foreach(var gItem in groups)
							{
								if(gItem.TheGroupCategory.GroupCategoryID == gcItem.GroupCategoryID)
								{
									var gListItem = new ListItem(gItem.GroupName, gItem.GroupID.ToString());

									ddlGroups.Items.Add(gListItem);
								}
							}
						}
					}
				}
			}
		}

		private void BindData()
		{
			rptGroupKPIProgressData.DataSource = GetDataSource();
			rptGroupKPIProgressData.DataBind();
		}

		private List<Group> GetDataSource()
		{
			var result = new List<Group>();

			if(_GroupRepository == null)
			{
				_GroupRepository = new GroupRepository();
			}

			if(ddlGroups.SelectedValue.Equals("0"))
			{
				result = _GroupRepository.GetGroupWithKPIAndProgressByGroupCategory(0);
			} // 全部单位
			else if(ddlGroups.SelectedItem.Text.Contains("---"))
			{
				var theGroupCategoryID = int.Parse(ddlGroups.SelectedValue);

				result = _GroupRepository.GetGroupWithKPIAndProgressByGroupCategory(theGroupCategoryID);
			} // 第一板块或第二板块单位
			else
			{
				var theGroupID = int.Parse(ddlGroups.SelectedValue);

				var theGroup = _GroupRepository.GetTheGroup(theGroupID);

				if(theGroup != null)
				{
					result.Add(theGroup);
				}
			} // 指定单位

			return result;
		}

		private void BuildGroupSheet(ISheet sheet, Group g)
		{
			if(g != null && sheet != null)
			{
				var headerRow = sheet.CreateRow(0);
				IFont hFont = sheet.Workbook.CreateFont();
				hFont.Boldweight = 18;
				hFont.FontHeightInPoints = 18;

				ICellStyle hStyle = sheet.Workbook.CreateCellStyle();
				hStyle.SetFont(hFont);
				hStyle.Alignment = HorizontalAlignment.CENTER;

				ICellStyle contentStyle = sheet.Workbook.CreateCellStyle();
				contentStyle.VerticalAlignment = VerticalAlignment.TOP;
				contentStyle.WrapText = true;
				contentStyle.Alignment = HorizontalAlignment.LEFT;

				ICellStyle numStyle = sheet.Workbook.CreateCellStyle();
				numStyle.Alignment = HorizontalAlignment.CENTER;

				var hCell0 = headerRow.CreateCell(0);
				hCell0.SetCellValue("单位");
				hCell0.CellStyle = hStyle;
				var hCell1 = headerRow.CreateCell(1);
				hCell1.SetCellValue("序号");
				hCell1.CellStyle = hStyle;
				var hCell2 = headerRow.CreateCell(2);
				hCell2.SetCellValue("指标内容");
				hCell2.CellStyle = hStyle;
				var hCell3 = headerRow.CreateCell(3);
				hCell3.SetCellValue("完成情况");
				hCell3.CellStyle = hStyle;

				var i = 0;
				for(; i < g.ListKPIs.Count; i++)
				{
					var kpi = g.ListKPIs[i];

					var itemRow = sheet.CreateRow(i + 1);

					var groupCell = itemRow.CreateCell(0);

					if(i == 0)
					{
						groupCell.SetCellValue(g.GroupShortName);
					}

					var numCell = itemRow.CreateCell(1);
					numCell.SetCellValue((i + 1).ToString());
					numCell.CellStyle = numStyle;

					var kpiContentCell = itemRow.CreateCell(2);
					kpiContentCell.CellStyle = contentStyle;
					kpiContentCell.SetCellValue(kpi.KPIContent);

					var progressCell = itemRow.CreateCell(3);

					progressCell.CellStyle = contentStyle;

					if(kpi.TheKPIProgress != null)
					{
						if(!string.IsNullOrWhiteSpace(kpi.TheKPIProgress.Quarter1Progress))
						{
							progressCell.SetCellValue(CommonHelper.HtmlStripTags(kpi.TheKPIProgress.Quarter1Progress));
						}
						else if(!string.IsNullOrWhiteSpace(kpi.TheKPIProgress.Quarter2Progress))
						{
							progressCell.SetCellValue(CommonHelper.HtmlStripTags(kpi.TheKPIProgress.Quarter2Progress));
						}
						else if(!string.IsNullOrWhiteSpace(kpi.TheKPIProgress.Quarter3Progress))
						{
							progressCell.SetCellValue(CommonHelper.HtmlStripTags(kpi.TheKPIProgress.Quarter3Progress));
						}
						else if(!string.IsNullOrWhiteSpace(kpi.TheKPIProgress.Quarter4Progress))
						{
							progressCell.SetCellValue(CommonHelper.HtmlStripTags(kpi.TheKPIProgress.Quarter4Progress));
						}
					}
				}

				sheet.AddMergedRegion(new CellRangeAddress(1, i, 0, 0));
				sheet.SetColumnWidth(2, 65 * 256);
				sheet.SetColumnWidth(3, 65 * 256);

			}
		}
	}
}